{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d124d22-de73-436b-86cd-9b162b469be8",
   "metadata": {
    "id": "2d124d22-de73-436b-86cd-9b162b469be8"
   },
   "outputs": [],
   "source": [
    "%pip install langchain_community\n",
    "%pip install langchain_experimental\n",
    "%pip install langchain-openai\n",
    "%pip install langchainhub\n",
    "%pip install chromadb\n",
    "%pip install langchain\n",
    "%pip install python-dotenv\n",
    "%pip install PyPDF2 -q --user\n",
    "%pip install rank_bm25\n",
    "%pip install langchain_core"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f884314f-870c-4bfb-b6c1-a5b4801ec172",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "executionInfo": {
     "elapsed": 4690,
     "status": "ok",
     "timestamp": 1716948148440,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "f884314f-870c-4bfb-b6c1-a5b4801ec172",
    "outputId": "76ea9fdd-5ba5-48f7-be31-351b68a76355"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import openai\n",
    "from langchain_openai import ChatOpenAI, OpenAIEmbeddings\n",
    "from langchain import hub\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.runnables import RunnablePassthrough\n",
    "import chromadb\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain_core.runnables import RunnableParallel\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from PyPDF2 import PdfReader\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_core.documents.base import Document\n",
    "from langchain_community.retrievers import BM25Retriever\n",
    "from langchain.retrievers import EnsembleRetriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "eba3468a-d7c2-4a79-8df2-c335542950f2",
   "metadata": {
    "executionInfo": {
     "elapsed": 278,
     "status": "ok",
     "timestamp": 1716948177675,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "eba3468a-d7c2-4a79-8df2-c335542950f2"
   },
   "outputs": [],
   "source": [
    "# variables\n",
    "_ = load_dotenv(dotenv_path='env.txt')\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')\n",
    "openai.api_key = os.environ['OPENAI_API_KEY']\n",
    "llm = ChatOpenAI(model_name=\"gpt-4o\", temperature=0)\n",
    "embedding_function = OpenAIEmbeddings()\n",
    "pdf_path = \"google-2023-environmental-report.pdf\"\n",
    "collection_name = \"google_environmental_report\"\n",
    "str_output_parser = StrOutputParser()\n",
    "user_query = \"What are Google's environmental initiatives?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d3ad428a-3eb6-40ec-a1a5-62565ead1e5b",
   "metadata": {
    "id": "d3ad428a-3eb6-40ec-a1a5-62565ead1e5b"
   },
   "outputs": [],
   "source": [
    "#### INDEXING ####"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "98ccda2c-0f4c-41c5-804d-2227cdf35aa7",
   "metadata": {
    "executionInfo": {
     "elapsed": 10611,
     "status": "ok",
     "timestamp": 1716948215859,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "98ccda2c-0f4c-41c5-804d-2227cdf35aa7"
   },
   "outputs": [],
   "source": [
    "# PDF Loader\n",
    "docs = []\n",
    "with open(pdf_path, \"rb\") as pdf_file:\n",
    "    pdf_reader = PdfReader(pdf_file)\n",
    "    pdf_text = \"\".join(page.extract_text() for page in pdf_reader.pages)\n",
    "    docs = [Document(page_content=page) for page in pdf_text.split(\"\\n\\n\")]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "855b6438-6c51-4b25-b799-36fb7b592bf5",
   "metadata": {
    "id": "855b6438-6c51-4b25-b799-36fb7b592bf5"
   },
   "outputs": [],
   "source": [
    "# RecursiveCharacterTextSplitter\n",
    "recursive_splitter = RecursiveCharacterTextSplitter(\n",
    "    separators=[\"\\n\\n\", \"\\n\", \". \", \" \", \"\"],\n",
    "    chunk_size=1000,\n",
    "    chunk_overlap=200\n",
    ")\n",
    "splits = recursive_splitter.split_documents(docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8a634467-26aa-4a04-b1de-8f248056cb7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "dense_documents = [Document(page_content=doc.page_content, metadata={\"id\": str(i), \"search_source\": \"dense\"}) for i, doc in enumerate(splits)]\n",
    "sparse_documents = [Document(page_content=doc.page_content, metadata={\"id\": str(i), \"search_source\": \"sparse\"}) for i, doc in enumerate(splits)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6b13568c-d633-464d-8c43-0d55f34cc8c1",
   "metadata": {
    "executionInfo": {
     "elapsed": 4507,
     "status": "ok",
     "timestamp": 1716948724972,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "6b13568c-d633-464d-8c43-0d55f34cc8c1"
   },
   "outputs": [],
   "source": [
    "# Chroma Vector Store\n",
    "chroma_client = chromadb.Client()\n",
    "vectorstore = Chroma.from_documents(\n",
    "    documents=dense_documents,\n",
    "    embedding=embedding_function,\n",
    "    collection_name=collection_name,\n",
    "    client=chroma_client\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "749fcce7-3203-49e8-a62f-ecf2edce4570",
   "metadata": {
    "executionInfo": {
     "elapsed": 128,
     "status": "ok",
     "timestamp": 1716948726221,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "749fcce7-3203-49e8-a62f-ecf2edce4570"
   },
   "outputs": [],
   "source": [
    "dense_retriever = vectorstore.as_retriever(search_kwargs={\"k\": 10})\n",
    "sparse_retriever = BM25Retriever.from_documents(sparse_documents, k=10)\n",
    "ensemble_retriever = EnsembleRetriever(retrievers=[dense_retriever, sparse_retriever], weights=[0.5, 0.5], c=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6ce8df01-925b-45b5-8fb8-17b5c40c581f",
   "metadata": {
    "id": "6ce8df01-925b-45b5-8fb8-17b5c40c581f"
   },
   "outputs": [],
   "source": [
    "#### RETRIEVAL and GENERATION ####"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "fac053d8-b871-4b50-b04e-28dec9fb3b0f",
   "metadata": {
    "executionInfo": {
     "elapsed": 262,
     "status": "ok",
     "timestamp": 1716948727550,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "fac053d8-b871-4b50-b04e-28dec9fb3b0f"
   },
   "outputs": [],
   "source": [
    "# Prompt\n",
    "prompt = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    You are an environment expert assisting others in \n",
    "    understanding what large companies are doing to \n",
    "    improve the environment. Use the following pieces \n",
    "    of retrieved context with information about what \n",
    "    a particular company is doing to improve the \n",
    "    environment to answer the question. \n",
    "    \n",
    "    If you don't know the answer, just say that you don't know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: {context} \n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "952fe678-4da9-4e2a-9801-33858884f21e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_variables=['context', 'question'] template=\"\\n    You are an environment expert assisting others in \\n    understanding what large companies are doing to \\n    improve the environment. Use the following pieces \\n    of retrieved context with information about what \\n    a particular company is doing to improve the \\n    environment to answer the question. \\n    \\n    If you don't know the answer, just say that you don't know.\\n    \\n    Question: {question} \\n    Context: {context} \\n    \\n    Answer:\\n    \"\n"
     ]
    }
   ],
   "source": [
    "print(prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "848493dc-96e1-4816-89bf-01f43f39aa49",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "    You are an environment expert assisting others in \n",
      "    understanding what large companies are doing to \n",
      "    improve the environment. Use the following pieces \n",
      "    of retrieved context with information about what \n",
      "    a particular company is doing to improve the \n",
      "    environment to answer the question. \n",
      "    \n",
      "    If you don't know the answer, just say that you don't know.\n",
      "    \n",
      "    Question: {question} \n",
      "    Context: {context} \n",
      "    \n",
      "    Answer:\n",
      "    \n"
     ]
    }
   ],
   "source": [
    "print(prompt.template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "aa9a2a31-528b-444c-8390-8f2719838ade",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt for marketing speak\n",
    "prompt2 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to help a marketing team create a \n",
    "    description for the website about the environmental\n",
    "    initiatives our clients are promoting.\n",
    "\n",
    "    Write a marketing description based on the information \n",
    "    provided in the context delimited by triple backticks. \n",
    "    \n",
    "    If you don't know the answer, just say that you don't know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}``` \n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "77693ab3-15d4-48ad-b544-21d4f77ced4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt for shorter output\n",
    "prompt3 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to help a marketing team create a \n",
    "    description for the website about the environmental\n",
    "    initiatives our clients are promoting.\n",
    "\n",
    "    Write a marketing description based on the information \n",
    "    provided in the context delimited by triple backticks. \n",
    "    \n",
    "    If you don't know the answer, just say that you don't know.\n",
    "\n",
    "    Use at most 50 words.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6531c65e-2657-4330-9718-9da0df3e0ee3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt for focus on area\n",
    "prompt4 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to help a marketing team create a \n",
    "    description for the website about the environmental\n",
    "    initiatives our clients are promoting.\n",
    "\n",
    "    Write a marketing description based on the information \n",
    "    provided in the context delimited by triple backticks. \n",
    "\n",
    "    The description is intended for a technology audience, \n",
    "    so this should focus on only the aspects of the company's \n",
    "    efforts that relate to using technology.\n",
    "\n",
    "    If you don't know the answer, just say that you don't know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}``` \n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "de39d0b9-c79a-4b94-b463-99dcc8f29588",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt for shorter output with a summary\n",
    "prompt5 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    Summarize the retrieved context below, delimited by \n",
    "    triple backticks, in at most 30 words.\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ee1f963c-1488-4c26-9c8c-18c0a2345e69",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt for shorter output with a summary and a focus\n",
    "prompt6 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    Summarize the retrieved context below, delimited by \n",
    "    triple backticks, in at most 30 words, and focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. \n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "1d4f1319-4527-45b1-8435-36ebb032a400",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prompt for shorter output using extract and focus \n",
    "prompt7 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. Limit to 30 words.\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "28ac5b4e-0431-481d-b44e-0a5bdf76540a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sentiment analysis \n",
    "prompt8 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. Limit to 30 words.\n",
    "\n",
    "    After this summary, determine what the sentiment \n",
    "    of context is, providing your answer as a single word, \n",
    "    either \"positive\" or \"negative\". \n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c5fb706f-7147-46b8-8017-1cd1b9d0477a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Product name extraction\n",
    "prompt9 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. Limit to 30 words.\n",
    "\n",
    "    After this summary, determine any specific products\n",
    "    that are identified in the context below, delimited \n",
    "    by triple backticks.  Indicate that this is a list\n",
    "    of related products with the words 'Related products: '\n",
    "    and then list those product names after those words.\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "5dae34e9-1059-4259-a354-3076542153df",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Topic extraction\n",
    "prompt10 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. Limit to 30 words.\n",
    "\n",
    "    After this summary, determine eight topics that are \n",
    "    being discussed in the context below delimited \n",
    "    by triple backticks.  \n",
    "    Make each item one or two words long. \n",
    "    Indicate that this is a list of related topics \n",
    "    with the words 'Related topics: '\n",
    "    and then list those topics after those words.\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "8d1074a1-21ae-4f8e-905b-c4b1bbdddc48",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Language transformation\n",
    "prompt11 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. Limit to 30 words.\n",
    "\n",
    "    Translate the summary into three additional languages,\n",
    "    Spanish, French, and English Pirate:\n",
    "    labeling each language with a format like this:\n",
    "    English: [summary]\n",
    "    \n",
    "    Spanish: [summary]\n",
    "    \n",
    "    French: [summary]\n",
    "    \n",
    "    English pirate: [summary]\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ce35624b-9036-4241-8ef2-72064e7c7d0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Tone transformation\n",
    "prompt12 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness of \n",
    "    their products. Limit to 30 words.\n",
    "\n",
    "    After providing the summary, translate the summary \n",
    "    into an email format with a more friendly and \n",
    "    casual tone.\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "e464a215-00e7-4f1d-8f06-062cf5824906",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Expand on a short text\n",
    "prompt13 = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Your task is to generate a short summary of what a \n",
    "    company is doing to improve the environment. \n",
    "\n",
    "    From the retrieved context below, delimited by \n",
    "    triple backticks, extract the information focusing \n",
    "    on any aspects that mention the eco-friendliness \n",
    "    of their products. Limit to 30 words.\n",
    "\n",
    "    After providing the summary, provide a broader\n",
    "    description of what the company is doing to \n",
    "    improve the environment and explain how this \n",
    "    can be useful to investors in that company.  \n",
    "    \n",
    "    For this broader description, do not use any of \n",
    "    the data provided in the context below, using \n",
    "    only the summary you have generated as the basis \n",
    "    for this description.\n",
    "    \n",
    "    If you don't know the answer, just say that you don't \n",
    "    know.\n",
    "    \n",
    "    Question: {question} \n",
    "    Context: ```{context}```\n",
    "    \n",
    "    Answer:\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "5ef30632-13dd-4a34-af33-cb8fab94f169",
   "metadata": {
    "executionInfo": {
     "elapsed": 116,
     "status": "ok",
     "timestamp": 1716948728500,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "5ef30632-13dd-4a34-af33-cb8fab94f169"
   },
   "outputs": [],
   "source": [
    "# Relevance check prompt\n",
    "relevance_prompt_template = PromptTemplate.from_template(\n",
    "    \"\"\"\n",
    "    Given the following question and retrieved context, determine if the context is relevant to the question.\n",
    "    Provide a score from 1 to 5, where 1 is not at all relevant and 5 is highly relevant.\n",
    "    Return ONLY the numeric score, without any additional text or explanation.\n",
    "\n",
    "    Question: {question}\n",
    "    Retrieved Context: {retrieved_context}\n",
    "\n",
    "    Relevance Score:\"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "aabb08a2-2d72-4d1a-8604-2ca89b324187",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "    Given the following question and retrieved context, determine if the context is relevant to the question.\n",
      "    Provide a score from 1 to 5, where 1 is not at all relevant and 5 is highly relevant.\n",
      "    Return ONLY the numeric score, without any additional text or explanation.\n",
      "\n",
      "    Question: {question}\n",
      "    Retrieved Context: {retrieved_context}\n",
      "\n",
      "    Relevance Score:\n"
     ]
    }
   ],
   "source": [
    "print(relevance_prompt_template.template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "e8975479-b3e3-481d-ad7b-08b4eb3faaef",
   "metadata": {
    "executionInfo": {
     "elapsed": 119,
     "status": "ok",
     "timestamp": 1716948730384,
     "user": {
      "displayName": "",
      "userId": ""
     },
     "user_tz": 240
    },
    "id": "e8975479-b3e3-481d-ad7b-08b4eb3faaef"
   },
   "outputs": [],
   "source": [
    "# Post-processing\n",
    "def format_docs(docs):\n",
    "    return \"\\n\\n\".join(doc.page_content for doc in docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "d6d7991f-24d0-47ea-b7ff-3ab2b8e12816",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_score(llm_output):\n",
    "    try:\n",
    "        score = float(llm_output.strip())\n",
    "        return score\n",
    "    except ValueError:\n",
    "        return 0\n",
    "\n",
    "# Chain it all together with LangChain\n",
    "def conditional_answer(x):\n",
    "    relevance_score = extract_score(x['relevance_score'])\n",
    "    if relevance_score < 4:\n",
    "        return \"I don't know.\"\n",
    "    else:\n",
    "        return x['answer']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "4f372a3d-b323-4fd5-8f6d-3005684fc0eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "rag_chain_from_docs = (\n",
    "    RunnablePassthrough.assign(context=(lambda x: format_docs(x[\"context\"])))\n",
    "    | RunnableParallel(\n",
    "        {\n",
    "            \"relevance_score\": (\n",
    "                RunnablePassthrough()\n",
    "                | (lambda x: relevance_prompt_template.format(question=x['question'], retrieved_context=x['context']))\n",
    "                | llm\n",
    "                | str_output_parser\n",
    "            ), \n",
    "             \"answer\": (\n",
    "                RunnablePassthrough()\n",
    "                | prompt\n",
    "                | llm\n",
    "                | str_output_parser\n",
    "            )\n",
    "        }\n",
    "    )\n",
    "    | RunnablePassthrough().assign(final_answer=conditional_answer)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "6d69171d-c68e-412b-96fa-f681fd51c92f",
   "metadata": {},
   "outputs": [],
   "source": [
    "rag_chain_with_source = RunnableParallel(\n",
    "    {\"context\": ensemble_retriever, \"question\": RunnablePassthrough()}\n",
    ").assign(answer=rag_chain_from_docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "ac8d4fef-04ca-426c-b742-a367818209ea",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original Question: What are Google's environmental initiatives?\n",
      "\n",
      "Relevance Score: 5\n",
      "\n",
      "Final Answer:\n",
      "Google has implemented a comprehensive set of environmental initiatives aimed at improving sustainability and reducing its environmental impact. Here are some key aspects of Google's environmental initiatives:\n",
      "\n",
      "1. **Empowering Individuals**:\n",
      "   - Google has developed sustainability features in its products, such as eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. These features have helped millions of people make more sustainable choices.\n",
      "\n",
      "2. **Working Together**:\n",
      "   - Google collaborates with various partners and customers to advance technology for sustainability. For example, Google Cloud provides data analytics tools to help organizations optimize their operations and reduce environmental impact. Google also supports initiatives like the iMasons Climate Accord and the ReFED Catalytic Grant Fund to drive industry-wide change.\n",
      "\n",
      "3. **Operating Sustainably**:\n",
      "   - Google aims to operate its business sustainably by focusing on net-zero carbon emissions, water stewardship, and a circular economy. For instance, Google's Bay View campus is all-electric, net water-positive, and incorporates principles of circular design. Google also invests in renewable energy projects, such as the Golden Hills wind farm in California.\n",
      "\n",
      "4. **Net-Zero Carbon**:\n",
      "   - Google is committed to achieving net-zero carbon emissions. The company has invested in renewable energy projects and works with suppliers to reduce their energy consumption and greenhouse gas (GHG) emissions.\n",
      "\n",
      "5. **Water Stewardship**:\n",
      "   - Google's Bay View campus features a stormwater retention pond and other water stewardship initiatives to manage water resources responsibly.\n",
      "\n",
      "6. **Circular Economy**:\n",
      "   - Google is working towards a circular economy by using renewable materials in its products and aiming for zero waste to landfill certification at its manufacturing sites.\n",
      "\n",
      "7. **Public Policy and Advocacy**:\n",
      "   - Google engages in public policy advocacy to support the creation of low-carbon economies. The company supports the United Nations Framework Convention on Climate Change (UNFCCC) and the Paris Agreement.\n",
      "\n",
      "8. **Data and Technology for Sustainability**:\n",
      "   - Google leverages its expertise in data and technology to support sustainability efforts. This includes tools like Google Earth Engine, which provides insights on environmental changes, and the development of AI solutions to reduce emissions and optimize resource use.\n",
      "\n",
      "9. **Supporting Innovation**:\n",
      "   - Google invests in sustainability-focused accelerators and supports early-stage innovations aimed at tackling climate change and other environmental challenges.\n",
      "\n",
      "10. **Supply Chain Management**:\n",
      "    - Google works with its suppliers to ensure they adhere to environmental standards and reduce their environmental impact. This includes regular audits and compliance checks.\n",
      "\n",
      "These initiatives reflect Google's commitment to sustainability and its efforts to make a positive impact on the environment through technology, collaboration, and responsible business practices.\n",
      "\n",
      "\n",
      "Retrieved Documents:\n",
      "Document 1: Document ID: 451 source: dense\n",
      "Content:\n",
      "Empowering individuals:  \n",
      "A parking lot full of electric vehicles lined up outside a Google office, \n",
      "plugged into charging stations.\n",
      "Working together:  \n",
      "Satellite-derived Earth Engine image showing seasonal agricultural peaks \n",
      "near the Columbia and Snake Rivers in Washington state. The perfectly round fields are center pivot irrigated corn and wheat maturing in different months. Data source: Landsat 8, U.S. Geological Survey.\n",
      "Operating sustainably:  \n",
      "A view of our Bay View campus with the events center in the foreground \n",
      "and a Google brandmark sculpture. (Photo: Iwan Baan)\n",
      "Net-zero carbon:  \n",
      "Golden Hills wind farm in California (43 MW for Google)\n",
      "Water stewardship:  \n",
      "Our Bay View campus, as seen from across its stormwater retention pond. (Photo: Iwan Baan)\n",
      "Circular economy:  \n",
      "A closeup of many small, broken circuit boards in a pile. Our approach\n",
      "\n",
      "Document 2: Document ID: 150 source: sparse\n",
      "Content:\n",
      "sustainability, and we’re partnering with them to develop decarbonization roadmaps and build essential data infrastructure to accurately quantify emissions and reductions across the value chain.\n",
      "We engage with our suppliers—including hardware \n",
      "manufacturing and indirect services suppliers—to help reduce their energy consumption and GHG emissions, as stated in our Supplier Code of Conduct , which all \n",
      "suppliers are required to sign. We assess suppliers’ practices to report, manage, and reduce their emissions and incorporate this into our supplier scorecard.\n",
      "Reporting  \n",
      "environmental data\n",
      "We expect all our suppliers to report environmental data,\n",
      "\n",
      "Document 3: Document ID: 311 source: dense\n",
      "Content:\n",
      "In 2022, we audited a subset of our suppliers to verify \n",
      "compliance for the following environmental criteria: implementation of environmental management systems, environmental permits and reporting, product content restrictions, and resource efficiency, as well as management of hazardous substances, wastewater,  solid waste, and air emissions.\n",
      "Googlers chat among indoor plants at our Pier 57 office in New York City.   79\n",
      "2023 Environmental Report  Public policy and advocacy\n",
      "We know that strong public policy action is critical to \n",
      "creating prosperous, equitable, and resilient low-carbon economies around the world. \n",
      "The United Nations Framework Convention on Climate \n",
      "Change (UNFCCC)’s 2015 Paris Agreement states that humanity must “keep global temperature rise this century well below 2°C above pre-industrial levels.”\n",
      " 143 Google\n",
      "\n",
      "Document 4: Document ID: 12 source: dense\n",
      "Content:\n",
      "The opportunity we have through our products and \n",
      "platforms is reflected in our updated environmental sustainability strategy, which focuses on where we can make the most significant positive impact. Our work is organized around three key pillars: empowering individuals to take action, working together with our partners and customers, and operating our business sustainably.\n",
      "In 2022, we reached our goal to help 1 billion people \n",
      "make more sustainable choices through our products. We achieved this by offering sustainability features like eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. Looking ahead, our aspiration is to help individuals, cities, and other partners collectively reduce 1 gigaton of their carbon equivalent emissions annually by 2030.\n",
      " 2\n",
      "\n",
      "Document 5: Document ID: 309 source: sparse\n",
      "Content:\n",
      "that enable us to ensure that those we partner with are responsible environmental stewards. Along with having suppliers evaluate their operations, we perform our own ongoing due diligence and audits to verify compliance and to understand our supply chain’s current and potential risks.\n",
      "When we find that a supplier isn’t complying, we expect\n",
      "\n",
      "Document 6: Document ID: 298 source: sparse\n",
      "Content:\n",
      "2023 Environmental Report  Risk management\n",
      "Our Enterprise Risk Management (ERM) team is responsible \n",
      "for identifying, assessing, and reporting risks related to the company’s operations, financial performance, and reputation. As with financial, operational, and strategic risks, the team assesses environmental risks as part of the company’s overall risk management framework. The risks and opportunities identified through this process support public disclosures and inform Google’s environmental sustainability strategy. Our Chief Sustainability Officer and sustainability teams work to address risks by identifying opportunities to reduce the company’s environmental impacts from its operations and value chain, and through improving climate resilience. \n",
      "Climate-related \n",
      "risks\n",
      "Climate-related risks and opportunities have long time\n",
      "\n",
      "Document 7: Document ID: 344 source: dense\n",
      "Content:\n",
      "iMasons Climate AccordGoogle is a founding member and part of the governing body of the iMasons Climate Accord, a coalition united on carbon reduction in digital infrastructure.\n",
      "ReFEDIn 2022, to activate industry-wide change, Google provided anchor funding to kickstart the ReFED Catalytic Grant Fund, with the goal of accelerating and scaling food waste solutions.\n",
      "The Nature Conservancy (TNC)In 2022, Google supported three of the Nature Conservancy’s watershed projects in Chile and the United States, and Google.org supported a three-phased approach to catalyze active reforestation of kelp at impactful scales. Google.org also provided a grant to TNC to develop a machine-learning-powered timber-tracing API to stop deforestation in the Amazon at scale; a team of Google engineers is working full-time for six months with TNC to develop this product as part of the Google.org Fellowship Program.\n",
      "\n",
      "Document 8: Document ID: 13 source: dense\n",
      "Content:\n",
      "2\n",
      "After two years of condensed reporting, we’re sharing a deeper dive into our approach in one place in our 2023 Environmental Report. In 2022, we continued to make measurable progress in many key ways, such as:\n",
      "• We enhanced and launched new sustainabilityproduct features , such as eco-friendly routing in\n",
      "Maps, which is estimated to have helped preventmore than 1.2 million metric tons of carbon emissionsfrom launch through 2022—equivalent to takingapproximately 250,000 fuel-based cars off the roadfor a year.\n",
      " 3\n",
      "• We expanded the availability of Google EarthEngine —which provides access to reliable, up-to-\n",
      "date insights on how our planet is changing—toinclude businesses and governments worldwide as anenterprise-grade service through Google Cloud.• We opened our new Bay View campus , which is\n",
      "all-electric, net water-positive, restores over 17 acresof high-value nature, and incorporates the leadingprinciples of circular design.\n",
      "\n",
      "Document 9: Document ID: 328 source: sparse\n",
      "Content:\n",
      "Sustainable \n",
      "consumption of \n",
      "public goods (e.g., \n",
      "“right to repair”)Google submitted comments to the European Commission’s public consultation regarding \n",
      "the promotion of repair and reuse of goods. We shared our views on the core principles to \n",
      "consider when introducing policy measures to promote repair and reuse horizontally, and for \n",
      "smartphones and tablets specifically.\n",
      "Body of European \n",
      "Regulators \n",
      "for Electronic \n",
      "Communications \n",
      "(BEREC)Google responded to a questionnaire  by BEREC in view of the development of key performance \n",
      "indicators to characterize the environmental impact of electronic communications, networks, \n",
      "devices, and services. We provided information about our environmental reporting practices \n",
      "and suggestions to help identify which indicators would provide relevant environmental \n",
      "information.\n",
      "Engagement with coalitions and sustainability initiatives\n",
      "RE-Source PlatformGoogle is a strategic partner and steering committee member of the RE-Source Platform, the\n",
      "\n",
      "Document 10: Document ID: 115 source: dense\n",
      "Content:\n",
      "of over 140 partner organizations.\n",
      "The Google.org Impact Challenge on Climate Innovation supports breakthrough projects that use data and technology to \n",
      "accelerate climate action.\n",
      "The journey ahead\n",
      "From measuring and monitoring changes on the Earth’s surface, improving forecast and prediction models for flooding and wildfires, optimizing operations, combining disparate data sources, and designing more efficient products, we continue to leverage our expertise in technology and apply the latest advancements to help solve global challenges.\n",
      "We believe that by working together with our partners and \n",
      "customers, we can make a real difference in addressing the challenges of climate change and ecosystem degradation. LEARN MORE\n",
      "• Data Commons\n",
      "• Environmental Insights Explorer\n",
      "• Google Cloud sustainability\n",
      "• Google Earth Engine\n",
      "• Sustainability-focused accelerators   31\n",
      "2023 Environmental Report  Operating \n",
      "sustainably\n",
      "We’re showing the way forward \n",
      "through our own operationsOur ambition\n",
      "\n",
      "Document 11: Document ID: 415 source: sparse\n",
      "Content:\n",
      "chemistry\n",
      "• Governance and engagement - Risk management; Stakeholder engagement - Supplier \n",
      "engagement\n",
      "Engagement with external targets and initiatives related to sustainable \n",
      "supply chains • Wor king together - Our approach - Supporting partners - Cloud customers and  \n",
      "commercial partners\n",
      "• Governance and engagement - PartnershipsC12. Engagement\n",
      "Goals and targets Supplier environmental assessment-related targets• Introd uction - Targets and progress summary\n",
      "• Oper ating sustainably - Circular economy - Our approach - Working with suppliers\n",
      "Performance indicators New suppliers that were screened using environmental criteria • Governance and engagement - Risk management C12. Engagement\n",
      "Supplier renewable energy• Opera ting sustainably - Net-zero carbon - Our approach - Advancing carbon-free energy - \n",
      "CFE inv estmentsC2. Risks and opportunities\n",
      "Negative environmental impacts in the supply chain and actions taken• Oper ating sustainably - Circular economy - Supply chain\n",
      "\n",
      "Document 12: Document ID: 67 source: dense\n",
      "Content:\n",
      "Our approach\n",
      "Supporting partners\n",
      "Investing in breakthrough \n",
      "innovation\n",
      "Creating ecosystems for \n",
      "collaboration\n",
      "The journey ahead\n",
      "   21\n",
      "2023 Environmental Report  Our ambition\n",
      "We believe that Google has a unique \n",
      "opportunity that extends beyond reducing \n",
      "the environmental impacts of our own \n",
      "operations and value chain. By organizing \n",
      "information about our planet and making \n",
      "it actionable through technology and \n",
      "platforms, we can help partners and \n",
      "customers create even more positive impact.\n",
      "Digital technologies  play a critical role in industry \n",
      "transitions, allowing us to measure and track sustainability \n",
      "progress, optimize the use of resources, reduce \n",
      "greenhouse gas emissions, and enable a more circular \n",
      "economy. 50 Cloud computing and digital technologies \n",
      "underpin the transformation in many sectors, such as \n",
      "energy, transportation, and agriculture. Research  that \n",
      "we commissioned in 2022 found that 20%–25% of what’s \n",
      "required for the EU’s 2050 net-zero goal requires some\n",
      "\n",
      "Document 13: Document ID: 139 source: sparse\n",
      "Content:\n",
      "development and deployment of these materials.\n",
      "In 2022, we filed a patent for using machine \n",
      "learning technology to improve our ability to prevent emissions from refrigerant leaks.\n",
      "Data centers\n",
      "Google’s data centers are the engine of our company, powering products like Gmail, Google Cloud, Search, and YouTube for billions of people around the world. We’ve worked to make Google’s data centers some of the most efficient in the world, improving their environmental performance even as demand for our products has risen. We’ve done this by designing, building, and operating each one to maximize efficient use of energy, water, \n",
      "and ma\n",
      "terials.\n",
      "Our long-standing data center efficiency  efforts are\n",
      "\n",
      "Document 14: Document ID: 346 source: dense\n",
      "Content:\n",
      "World Business Council for Sustainable Development (WBCSD)Google has been a member of the WBCSD for several years and participates in a number of its initiatives. \n",
      "We’re a\n",
      "ctively involved in initiatives related to improving well-being for people and the planet, including  \n",
      "shifting diets, consumer behavior changes, and regenerative agriculture. \n",
      "World Resources Institute (WRI)Google has a 13-year long relationship with WRI for impact-focused collaboration. Some key projects include developing a near-real-time land cover dataset ( Dynamic World ), deforestation monitoring and alerts ( Global \n",
      "Forest Watch ), ending commodity-driven deforestation and accelerating restoration ( Forest Data Partnership ), \n",
      "measuring and mitigating extreme heat ( supported by Google.org ), and educating stakeholders on 24/7 CFE.   84\n",
      "2023 Environmental Report  Awards and recognition\n",
      "2022 CDP Climate Change A List  \n",
      "Alphabet has been named to CDP’s Climate Change A list,\n",
      "\n",
      "Document 15: Document ID: 432 source: sparse\n",
      "Content:\n",
      "2023 Environmental Report  market structures. If no such structure exists, then Google defines the grid \n",
      "region as the electricity-balancing authority where our data centers are \n",
      "located. Outside of the United States, the grid region most often refers to \n",
      "the geographic boundary of a country, because most grid system operators \n",
      "operate at the national level. Certain regions that span multiple countries \n",
      "are well interconnected and could be considered as one grid; however, \n",
      "our grid mix calculations already include import and export considerations \n",
      "and therefore take into account power flows from neighboring grids. In \n",
      "the future, we may update our definition as we work with grid operators to \n",
      "better understand how transmission constraints or congestion impact CFE \n",
      "measurement within and across grid regions.\n",
      "91 Contracted CFE is the hourly electricity production from clean energy \n",
      "projects whose electricity and associated environmental attributes are\n",
      "\n",
      "Document 16: Document ID: 111 source: dense\n",
      "Content:\n",
      "Googlers collaborate in the Event Center at our Bay View campus.   30\n",
      "2023 Environmental Report  Google for Startups\n",
      "By investing early in technologies aimed at tackling \n",
      "sustainability challenges like climate change, we have the potential to move the needle on sustainability and positively impact our planet. We have a portfolio of sustainability-focused accelerators , which support  \n",
      "early stage innovations to grow and scale.\n",
      "Google for Startups \n",
      "Accelerator\n",
      "Google for Startups is working to identify, support, and\n",
      "\n",
      "Document 17: Document ID: 91 source: sparse\n",
      "Content:\n",
      "EV Suitability Assessment helps organizations monitor their fleet of vehicles and make choices that minimize environmental impact.\n",
      "Data analytics tools from Google Cloud are also helping \n",
      "airlines. Lufthansa Group partnered with Google Cloud \n",
      "and Google Research to develop a platform that facilitates better planning and management of daily flight operations.\n",
      "We’re helping organizations harness \n",
      "the power of data and AI to drive more intelligent supply chains.Renewable energy\n",
      "Wind farms are an important source of carbon-free electricity, but wind can fluctuate depending on the weather. Through Google Cloud, customers like Engie  (a global energy and renewables supplier) can optimize their wind portfolio in short-term power markets by predicting wind power output 36 hours ahead of actual generation  and making optimal hourly delivery \n",
      "commitments to the grid, a full day in advance.  \n",
      "Sustainability partner \n",
      "solutions\n",
      "Partner solutions are important to scale the impact for our\n",
      "\n",
      "Document 18: Document ID: 66 source: dense\n",
      "Content:\n",
      "the United States for pre-owned products, such as used and refurbished products. The journey \n",
      "ahead\n",
      "While a single individual’s actions may seem small, when \n",
      "billions of people have the tools to make more sustainable decisions, they add up to have a meaningful impact on their communities and the entire planet. \n",
      "We’re excited by the opportunity to enable climate and \n",
      "environmental action far beyond Google’s direct impact, through information and innovation.\n",
      "LEARN MORE\n",
      " • Empowering with technology\n",
      " • Google Maps eco-friendly routing\n",
      " • Searching for sustainability with Google\n",
      " • Supporting a clean energy future with Nest Renew\n",
      " • The search for sustainability   20\n",
      "2023 Environmental Report  Working \n",
      "together\n",
      "We’re working together with our \n",
      "partners and customers to advance technology for sustainabilityOur ambition\n",
      "Our approach\n",
      "Supporting partners\n",
      "Investing in breakthrough \n",
      "innovation\n",
      "Creating ecosystems for \n",
      "collaboration\n",
      "The journey ahead\n",
      "   21\n",
      "2023 Environmental Report  Our ambition\n",
      "\n",
      "Document 19: Document ID: 22 source: sparse\n",
      "Content:\n",
      "cled/ Ongoing  36% 41% 2025our consumer hardware product portfolio by 2025 renewable material (see pg. 62 )\n",
      "% plastic-free Ongoing  Make product packaging 100% plastic-free by 2025 97% 96% 2025packaging (see pg. 63 )\n",
      "Significant  Achieve UL 2799 Zero Waste to Landfill certification at all final \n",
      "Supply chain % of sites certified 9% 90% 2022 progress  assembly consumer hardware manufacturing sites by 2022\n",
      "(see pg. 65 )   9\n",
      "2023 Environmental Report  \n",
      "Emerging opportunities\n",
      "As the world becomes increasingly aware of the need for sustainability, individuals, businesses, and communities are  \n",
      "looking for new ways to reduce their environmental impact. Artificial intelligence (AI) and the power of information to help individuals and organizations reduce emissions are two emerging opportunities that Google is focusing on to help build a more sustainable future.\n",
      "AI for sustainability\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Question - relevant question\n",
    "result = rag_chain_with_source.invoke(user_query)\n",
    "retrieved_docs = result['context']\n",
    "\n",
    "print(f\"Original Question: {user_query}\\n\")\n",
    "print(f\"Relevance Score: {result['answer']['relevance_score']}\\n\")\n",
    "print(f\"Final Answer:\\n{result['answer']['final_answer']}\\n\\n\")\n",
    "print(\"Retrieved Documents:\")\n",
    "for i, doc in enumerate(retrieved_docs, start=1):\n",
    "    print(f\"Document {i}: Document ID: {doc.metadata['id']} source: {doc.metadata['search_source']}\")\n",
    "    print(f\"Content:\\n{doc.page_content}\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "39a2994b-8938-497e-857b-c2b07c663830",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "Google has implemented a comprehensive set of environmental initiatives aimed at improving sustainability and reducing its environmental impact. Here are some key aspects of Google's environmental initiatives:\n",
       "\n",
       "1. **Empowering Individuals**:\n",
       "   - Google has developed sustainability features in its products, such as eco-friendly routing in Google Maps, energy efficiency features in Google Nest thermostats, and carbon emissions information in Google Flights. These features have helped millions of people make more sustainable choices.\n",
       "\n",
       "2. **Working Together**:\n",
       "   - Google collaborates with various partners and customers to advance technology for sustainability. For example, Google Cloud provides data analytics tools to help organizations optimize their operations and reduce environmental impact. Google also supports initiatives like the iMasons Climate Accord and the ReFED Catalytic Grant Fund to drive industry-wide change.\n",
       "\n",
       "3. **Operating Sustainably**:\n",
       "   - Google aims to operate its business sustainably by focusing on net-zero carbon emissions, water stewardship, and a circular economy. For instance, Google's Bay View campus is all-electric, net water-positive, and incorporates principles of circular design. Google also invests in renewable energy projects, such as the Golden Hills wind farm in California.\n",
       "\n",
       "4. **Net-Zero Carbon**:\n",
       "   - Google is committed to achieving net-zero carbon emissions. The company has invested in renewable energy projects and works with suppliers to reduce their energy consumption and greenhouse gas (GHG) emissions.\n",
       "\n",
       "5. **Water Stewardship**:\n",
       "   - Google's Bay View campus features a stormwater retention pond and other water stewardship initiatives to manage water resources responsibly.\n",
       "\n",
       "6. **Circular Economy**:\n",
       "   - Google is working towards a circular economy by using renewable materials in its products and aiming for zero waste to landfill certification at its manufacturing sites.\n",
       "\n",
       "7. **Public Policy and Advocacy**:\n",
       "   - Google engages in public policy advocacy to support the creation of low-carbon economies. The company supports the United Nations Framework Convention on Climate Change (UNFCCC) and the Paris Agreement.\n",
       "\n",
       "8. **Data and Technology for Sustainability**:\n",
       "   - Google leverages its expertise in data and technology to support sustainability efforts. This includes tools like Google Earth Engine, which provides insights on environmental changes, and the development of AI solutions to reduce emissions and optimize resource use.\n",
       "\n",
       "9. **Supporting Innovation**:\n",
       "   - Google invests in sustainability-focused accelerators and supports early-stage innovations aimed at tackling climate change and other environmental challenges.\n",
       "\n",
       "10. **Supply Chain Management**:\n",
       "    - Google works with its suppliers to ensure they adhere to environmental standards and reduce their environmental impact. This includes regular audits and compliance checks.\n",
       "\n",
       "These initiatives reflect Google's commitment to sustainability and its efforts to make a positive impact on the environment through technology, collaboration, and responsible business practices."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "markdown_text = result['answer']['final_answer']\n",
    "display(Markdown(markdown_text))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87cb96b1-3597-45c8-b6cc-d3eade50412d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "name": "CHAPTER11-2_TEXT_SPLITTERS.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
